<template>
  <div class="schedule-container">
    <el-card shadow="never">
      <template #header>
        <div class="header-actions">
          <h2>员工排班表</h2>
          <div class="view-controls">
            <!-- 月份选择器 -->
            <div class="month-selector">
              <div class="month-header">
                <el-button text @click="prevYear">
                  <el-icon><DArrowLeft /></el-icon>
                </el-button>
                <span class="current-year">{{ currentDate.getFullYear() }}年</span>
                <el-button text @click="nextYear">
                  <el-icon><DArrowRight /></el-icon>
                </el-button>
              </div>
              <div class="month-grid">
                <div 
                  v-for="(month, index) in monthNames" 
                  :key="index" 
                  class="month-item" 
                  :class="{
                    'current-month': currentDate.getMonth() === index,
                    'selected-month': selectedMonth === index
                  }" 
                  @click="selectMonth(index)"
                >
                  {{ month }}
                </div>
              </div>
            </div>
            
            <el-button-group class="view-switcher">
              <el-button :type="currentView === 'day' ? 'primary' : ''" @click="switchView('day')">日</el-button>
              <el-button :type="currentView === 'week' ? 'primary' : ''" @click="switchView('week')">周</el-button>
              <el-button :type="currentView === 'month' ? 'primary' : ''" @click="switchView('month')">月</el-button>
            </el-button-group>
            
            <el-button 
              type="primary" 
              @click="handleSaveSchedule" 
              :loading="scheduleStore.loading"
              class="save-schedule-btn"
            >
              保存排班
            </el-button>
          </div>
        </div>
      </template>

      <div class="schedule-content">
        <!-- 批量删除功能区 -->
        <div class="batch-actions" v-if="currentView === 'month'">
          <el-select
            v-model="selectedEmployeeIds"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="选择要操作的员工"
            :remote-method="remoteSearchEmployees"
            :loading="employeeLoading"
            style="width: 250px; margin-right: 10px;"
          >
            <el-option
              v-for="employee in filteredEmployees"
              :key="employee.staffId"
              :label="employee.staffName"
              :value="employee.staffId"
            />
          </el-select>
          
          <el-date-picker 
            v-model="selectedRange" 
            type="daterange" 
            range-separator="至" 
            start-placeholder="开始日期" 
            end-placeholder="结束日期"
            :disabled-date="disabledDate"
            style="width: 350px; margin-right: 10px;"
          />
          
          <el-button 
            type="danger" 
            icon="Delete" 
            @click="batchDeleteSelectedRangeSchedules"
            :loading="batchDeleting"
            :disabled="!isBatchOperationValid"
          >
            批量删除选中员工的排班
          </el-button>
          
          <el-button 
            type="info" 
            text 
            @click="clearAllSelections"
            v-if="isRangeSelected || selectedEmployeeIds.length > 0"
          >
            清除选择
          </el-button>
        </div>

        <!-- 视图导航 -->
        <div class="view-navigation" v-if="currentView !== 'day'">
          <el-button-group>
            <el-button @click="prevPeriod">
              <el-icon><ArrowLeft /></el-icon>
              {{ currentView === 'week' ? '上周' : '上月' }}
            </el-button>
            <el-button @click="today">今天</el-button>
            <el-button @click="nextPeriod">
              {{ currentView === 'week' ? '下周' : '下月' }}
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </el-button-group>
          <span class="current-period">{{ periodTitle }}</span>
        </div>

        <!-- 月视图 -->
        <div v-if="currentView === 'month'" class="schedule-table">
          <el-table 
            :data="employeeList" 
            border 
            style="width: 100%" 
            height="600px"
            :row-class-name="tableRowClassName"
          >
            <el-table-column prop="staffName" label="姓名" fixed width="120" />
            <el-table-column prop="titleName" label="职称" fixed width="120" />
            <el-table-column prop="positionName" label="职位" fixed width="120" />
            <el-table-column 
              v-for="(day, index) in monthDays" 
              :key="index" 
              :label="day.label" 
              width="100"
              :class-name="(row) => getColumnClassName(row, day.date)"
            >
              <template #default="{ row }">
                <div class="day-cell" @click="handleCellClick(row, day.date)">
                  <template v-if="getEmployeeDayShifts(row.staffName, day.date).length">
                    <div 
                      v-for="(shift, shiftIndex) in getEmployeeDayShifts(row.staffName, day.date)" 
                      :key="shiftIndex"
                      class="shift-item" 
                      :class="getScheduleStatusClass(shift)"
                    >
                      <el-tooltip 
                        effect="dark" 
                        :content="`${shift.shiftName}\n${shift.startTime} - ${shift.endTime}`"
                        placement="top"
                      >
                        {{ shift.shiftName }}
                      </el-tooltip>
                    </div>
                  </template>
                  <span v-else class="no-schedule">无排班</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 周视图 -->
        <div v-if="currentView === 'week'" class="schedule-table">
          <el-table :data="employeeList" border style="width: 100%" height="600px">
            <el-table-column prop="staffName" label="姓名" fixed width="120" />
            <el-table-column prop="titleName" label="职称" fixed width="120" />
            <el-table-column prop="positionName" label="职位" fixed width="120" />
            <el-table-column 
              v-for="(day, index) in weekDays" 
              :key="index" 
              :label="day.label" 
              width="120"
              :class-name="day.isWeekend ? 'weekend-cell' : ''"
            >
              <template #default="{ row }">
                <div class="day-cell" @click="handleCellClick(row, day.date)">
                  <template v-if="getEmployeeDayShifts(row.staffName, day.date).length">
                    <div 
                      v-for="(shift, shiftIndex) in getEmployeeDayShifts(row.staffName, day.date)" 
                      :key="shiftIndex"
                      class="shift-item" 
                      :class="getScheduleStatusClass(shift)"
                    >
                      <el-tooltip 
                        effect="dark" 
                        :content="`${shift.shiftName}\n${shift.startTime} - ${shift.endTime}`"
                        placement="top"
                      >
                        {{ shift.shiftName }}
                      </el-tooltip>
                    </div>
                  </template>
                  <span v-else class="no-schedule">无排班</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 日视图 -->
        <div v-if="currentView === 'day'" class="day-view">
          <el-table :data="employeeList" border style="width: 100%">
            <el-table-column prop="staffName" label="姓名" width="150" />
            <el-table-column prop="titleName" label="职称" width="150" />
            <el-table-column prop="positionName" label="职位" width="150" />
            <el-table-column label="今日排班" width="300">
              <template #default="{ row }">
                <div class="day-cell">
                  <template v-if="getEmployeeDayShifts(row.staffName, currentDayDate).length">
                    <div 
                      v-for="(shift, shiftIndex) in getEmployeeDayShifts(row.staffName, currentDayDate)"
                      :key="shiftIndex" 
                      class="shift-item" 
                      :class="getScheduleStatusClass(shift)"
                    >
                      {{ shift.shiftName }} ({{ shift.startTime }} - {{ shift.endTime }})
                    </div>
                  </template>
                  <span v-else class="no-schedule">今日无排班</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>

    <!-- 排班设置对话框（双页面切换） -->
    <el-dialog 
      v-model="showScheduleDialog" 
      title="排班操作" 
      width="700px"
    >
      <!-- Tab 切换栏 -->
      <div class="dialog-tabs">
        <el-radio-group v-model="activeDialogTab" @change="switchDialogTab">
          <el-radio label="view">查看当前班次</el-radio>
          <el-radio label="setting">排班设置预览</el-radio>
        </el-radio-group>
      </div>

      <!-- 页面1：查看当前班次（标签化展示） -->
      <template v-if="activeDialogTab === 'view'">
        <div class="current-shift-view">
          <h3>当前班次信息</h3>
          <el-descriptions column="1" border>
            <el-descriptions-item label="员工姓名">{{ selectedEmployee.staffName || '未选择' }}</el-descriptions-item>
            <el-descriptions-item label="查询日期">{{ selectedDate || '未选择' }}</el-descriptions-item>
            <el-descriptions-item label="当前班次">
              <!-- 加载状态 -->
              <template v-if="loading">
                <div class="loading-shifts">
                  <el-skeleton :count="3" :loading="true" />
                </div>
              </template>
              
              <!-- 错误状态 -->
              <template v-else-if="error">
                <div class="error-text">{{ error }}</div>
              </template>
              
              <!-- 班次标签展示 -->
              <template v-else>
                <div class="shift-tags">
                  <!-- 已排班次标签（可关闭） -->
                  <el-tag 
                    v-for="(shift, idx) in getEmployeeDayShifts(selectedEmployee.staffName, selectedDate)" 
                    :key="idx" 
                    type="success" 
                    closable 
                    @close="handleDeleteShift(shift)"
                    class="shift-tag"
                  >
                    <span class="tag-name">{{ shift.shiftName }}</span>
                    <span class="tag-time">{{ shift.startTime }} - {{ shift.endTime }}</span>
                  </el-tag>
                  
                  <!-- 无班次提示 -->
                  <div v-if="!getEmployeeDayShifts(selectedEmployee.staffName, selectedDate).length" class="no-shift">
                    该日期暂无排班记录
                  </div>
                </div>
                
                <!-- 新增班次按钮 -->
                <el-button 
                  type="primary" 
                  size="small" 
                  class="add-shift-btn"
                  @click="openAddShiftDialog"
                >
                  <el-icon><Plus /></el-icon> 新增班次
                </el-button>
              </template>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </template>

      <!-- 页面2：排班设置预览 -->
      <template v-else>
        <el-form label-width="80px">
          <el-form-item label="员工姓名">
            <el-input v-model="selectedEmployee.staffName" disabled />
          </el-form-item>
          <el-form-item label="排班日期">
            <el-input v-model="selectedDate" disabled />
          </el-form-item>
          <el-form-item label="截止排班日期" prop="endDate">
            <el-date-picker 
              v-model="endDate" 
              type="date" 
              placeholder="选择截止日期" 
              style="width: 100%"
              :disabled-date="(date) => isDateDisabled(date, selectedDate)" 
            />
          </el-form-item>
          <el-form-item label="排班设置">
            <el-select 
              v-model="selectedSettingId" 
              placeholder="请选择排班设置" 
              style="width: 100%"
              :loading="scheSettingStore.loading" 
              @change="handleSettingChange"
            >
              <el-option 
                v-for="setting in scheduleSettings" 
                :key="setting.settingId" 
                :label="setting.settingName"
                :value="setting.settingId" 
              />
              <el-option v-if="!scheduleSettings.length" disabled label="暂无排班设置" value="" />
            </el-select>
          </el-form-item>
        </el-form>
      </template>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <el-button @click="showScheduleDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmSchedule"
          :disabled="activeDialogTab === 'setting' && (!selectedSettingId || !endDate || scheSettingStore.loading)"
        >
          {{ activeDialogTab === 'setting' ? '确定' : '关闭' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 新增班次对话框 -->
    <el-dialog 
      v-model="addShiftDialog" 
      title="新增班次" 
      width="500px"
    >
      <el-form label-width="80px">
        <el-form-item label="员工姓名">
          <el-input v-model="selectedEmployee.staffName" disabled />
        </el-form-item>
        <el-form-item label="排班日期">
          <el-input v-model="selectedDate" disabled />
        </el-form-item>
        <el-form-item label="选择班次" >
          <el-select 
            v-model="selectedAddShiftId" 
            placeholder="请选择激活的班次" 
            style="width: 100%"
            :loading="shiftStore.loading"
          >
            <el-option 
              v-for="shift in shiftStore.shifts" 
              :key="shift.shiftId" 
              :label="`${shift.shiftName} (${formatTime(shift.startTime)} - ${formatTime(shift.endTime)})`"
              :value="shift.shiftId" 
            />
            <el-option v-if="!shiftStore.shifts.length" disabled label="暂无可用班次" value="" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addShiftDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmAddShift"
          :disabled="!selectedAddShiftId || shiftStore.loading"
        >
          确认新增
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ArrowLeft, ArrowRight, DArrowLeft, DArrowRight, Plus, Delete } from '@element-plus/icons-vue'
import { useStaffStore } from '@/stores/system/staff'
import { useScheduleStore } from '@/stores/schedule/schedule'
import { useScheSettingStore } from '@/stores/schedule/setting'
import { useShiftStore } from '@/stores/schedule/shift'
import { ElMessage, ElSkeleton, ElTag, ElButton, ElMessageBox } from 'element-plus'
import type { ISchedule } from '@/api/schedule/schedule'
import type { IShift } from '@/api/schedule/shift'
import { useUserStore } from "@/stores/modules/user";

// 状态管理 - 仅使用store方法，不直接调用api
const staffStore = useStaffStore()
const scheduleStore = useScheduleStore()
const scheSettingStore = useScheSettingStore()
const shiftStore = useShiftStore()

// 当前部门ID
const currentDeptId = ref(useUserStore().userInfo.staff.deptId)

// 日期与视图管理
const currentDate = ref(new Date())
const currentView = ref<'day' | 'week' | 'month'>('month')
const selectedMonth = ref<number | null>(null)

// 弹窗相关状态
const showScheduleDialog = ref(false)
const selectedEmployee = ref<any>({})
const selectedDate = ref('')
const selectedSettingId = ref<string | number | null>(null)
const scheduleSettings = ref<any[]>([])
const selectedSetting = ref<any>(null)
const endDate = ref<Date | null>(null)

// 新增班次相关
const addShiftDialog = ref(false)
const selectedAddShiftId = ref<number | null>(null)

// 批量删除相关状态
const batchDeleting = ref(false)
const selectedRange = ref<[Date | null, Date | null]>([null, null])
const selectedEmployeeIds = ref<string[]>([])
const filteredEmployees = ref<any[]>([])
const employeeLoading = ref(false)

// 弹窗Tab控制
const activeDialogTab = ref<'view' | 'setting'>('setting')
const switchDialogTab = (tab: 'view' | 'setting') => {
  activeDialogTab.value = tab
  // 切换到查看页面时加载班次数据
  if (tab === 'view') {
    fetchAllActiveShifts()
  }
}

// 排班数据映射：key: "员工姓名_日期" → 班次数组
const scheduleMap = ref<Map<string, ISchedule[]>>(new Map())

// 基础数据
const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
const weekdays = ['日', '一', '二', '三', '四', '五', '六']
const employeeList = ref<any[]>([])

// 班次数据（通过store获取）
const loading = ref(false)
const error = ref<string | null>(null)

// 计算月视图天数
const monthDays = computed(() => {
  const days = []
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth()
  const daysInMonth = new Date(year, month + 1, 0).getDate()

  for (let i = 1; i <= daysInMonth; i++) {
    const date = new Date(year, month, i)
    const dayOfWeek = date.getDay()
    const isWeekend = dayOfWeek === 0 || dayOfWeek === 6
    const dateStr = formatDateToYMD(date)

    days.push({
      date: dateStr,
      label: `${month + 1}月${i}日\n星期${weekdays[dayOfWeek]}`,
      isWeekend
    })
  }
  return days
})

// 计算周视图天数
const weekDays = computed(() => {
  const days = []
  const current = new Date(currentDate.value)
  const dayOfWeek = current.getDay()
  const diff = dayOfWeek === 0 ? -6 : 1 - dayOfWeek
  const start = new Date(current)
  start.setDate(current.getDate() + diff)

  for (let i = 0; i < 7; i++) {
    const date = new Date(start)
    date.setDate(start.getDate() + i)
    const dayOfWeek = date.getDay()
    const isWeekend = dayOfWeek === 0 || dayOfWeek === 6
    const dateStr = formatDateToYMD(date)

    days.push({
      date: dateStr,
      label: `${date.getMonth() + 1}月${date.getDate()}日\n星期${weekdays[dayOfWeek]}`,
      isWeekend
    })
  }
  return days
})

// 当前周期标题
const periodTitle = computed(() => {
  if (currentView.value === 'month') {
    return `${currentDate.value.getFullYear()}年 ${monthNames[currentDate.value.getMonth()]}`
  } else if (currentView.value === 'week') {
    const current = new Date(currentDate.value)
    const dayOfWeek = current.getDay()
    const diff = dayOfWeek === 0 ? -6 : 1 - dayOfWeek
    const start = new Date(current)
    start.setDate(current.getDate() + diff)
    const end = new Date(start)
    end.setDate(start.getDate() + 6)
    return `${start.getMonth() + 1}月${start.getDate()}日 - ${end.getMonth() + 1}月${end.getDate()}日`
  } else {
    return `${currentDate.value.getFullYear()}年 ${currentDate.value.getMonth() + 1}月${currentDate.value.getDate()}日`
  }
})

// 当前日日期
const currentDayDate = computed(() => formatDateToYMD(currentDate.value))

// 判断日期是否在用户选择的范围内
const isInSelectedRange = (dateStr: string) => {
  if (!selectedRange.value[0] || !selectedRange.value[1]) return false;
  
  const start = formatDateToYMD(selectedRange.value[0]);
  const end = formatDateToYMD(selectedRange.value[1]);
  
  return dateStr >= start && dateStr <= end;
}

// 判断员工是否被选中
const isEmployeeSelected = (staffId: string) => {
  return selectedEmployeeIds.value.includes(staffId);
}

// 检查批量操作是否有效（是否选择了员工和有效的日期范围）
const isBatchOperationValid = computed(() => {
  return selectedEmployeeIds.value.length > 0 && 
         !!selectedRange.value[0] && 
         !!selectedRange.value[1] && 
         selectedRange.value[0] <= selectedRange.value[1];
})

// 检查是否选择了日期范围
const isRangeSelected = computed(() => {
  return !!selectedRange.value[0] || !!selectedRange.value[1];
})

// 获取员工某天的班次
const getEmployeeDayShifts = (staffName: string, date: string) => {
  const key = `${staffName}_${date}`
  return scheduleMap.value.get(key) || []
}

// 员工搜索方法
const remoteSearchEmployees = (query: string) => {
  if (query.trim() === '') {
    filteredEmployees.value = [];
    return;
  }
  
  employeeLoading.value = true;
  
  // 模拟远程搜索，实际项目中应该调用API
  setTimeout(() => {
    filteredEmployees.value = employeeList.value.filter(employee => 
      employee.staffName.toLowerCase().includes(query.toLowerCase())
    );
    employeeLoading.value = false;
  }, 300);
}

// 禁用未来日期选择（可选）
const disabledDate = (date: Date) => {
  // 可以根据需求禁用未来日期
  // return date > new Date();
  return false;
}

// 清除所有选择
const clearAllSelections = () => {
  selectedRange.value = [null, null];
  selectedEmployeeIds.value = [];
}

// 周期切换方法
const prevPeriod = () => {
  const newDate = new Date(currentDate.value)
  currentView.value === 'month'
    ? newDate.setMonth(newDate.getMonth() - 1)
    : newDate.setDate(newDate.getDate() - 7)
  currentDate.value = newDate
}

const nextPeriod = () => {
  const newDate = new Date(currentDate.value)
  currentView.value === 'month'
    ? newDate.setMonth(newDate.getMonth() + 1)
    : newDate.setDate(newDate.getDate() + 7)
  currentDate.value = newDate
}

const today = () => {
  currentDate.value = new Date()
}

// 日期格式化
const formatDateToYMD = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 时间格式化（去掉秒）
const formatTime = (timeStr: string) => {
  if (!timeStr) return '';
  return timeStr.length >= 5 ? timeStr.substring(0, 5) : timeStr;
}

// 班次状态与时间段样式
const getScheduleStatusClass = (shift: ISchedule) => {
  // 先处理特殊状态（如请假）
  if (shift.status === 0) return 'schedule-leave';
  
  // 解析开始时间，判断时间段
  const startTime = shift.startTime || shift.scheShift?.startTime || '';
  if (!startTime) return 'shift-default'; // 默认样式
  
  // 提取小时数（处理 HH:MM:SS 格式）
  const hour = parseInt(startTime.split(':')[0], 10);
  
  // 根据小时判断时间段
  if (hour >= 6 && hour < 12) return 'shift-morning'; // 早班
  if (hour >= 12 && hour < 18) return 'shift-noon'; // 中班
  if (hour >= 18 && hour < 24) return 'shift-evening'; // 晚班
  return 'shift-night'; // 夜班（0-6点）
};

// 表格行样式（标记选中的员工）
const tableRowClassName = ({ row }: { row: any }) => {
  return isEmployeeSelected(row.staffId) ? 'selected-employee-row' : '';
};

// 表格列样式（标记选中员工的选中日期范围）
const getColumnClassName = (row: any, date: string) => {
  if (isEmployeeSelected(row.staffId) && isInSelectedRange(date)) {
    return 'selected-employee-date-cell';
  } else if (isInSelectedRange(date)) {
    return 'selected-date-cell';
  } else if (row.isWeekend) {
    return 'weekend-cell';
  }
  return '';
};

// 月份选择
const selectMonth = (monthIndex: number) => {
  selectedMonth.value = monthIndex
  const newDate = new Date(currentDate.value)
  newDate.setMonth(monthIndex)
  currentDate.value = newDate
}

// 年份切换
const prevYear = () => {
  const newDate = new Date(currentDate.value)
  newDate.setFullYear(newDate.getFullYear() - 1)
  currentDate.value = newDate
}

const nextYear = () => {
  const newDate = new Date(currentDate.value)
  newDate.setFullYear(newDate.getFullYear() + 1)
  currentDate.value = newDate
}

// 排班设置变更
const handleSettingChange = (settingId: string | number) => {
  selectedSetting.value = scheduleSettings.value.find(s => s.settingId === settingId) || null
}

// 单元格点击：打开排班对话框
const handleCellClick = async (employee: any, date: string) => {
  initEmployeeData();
  
  selectedEmployee.value = employee
  selectedDate.value = date
  selectedSettingId.value = null
  selectedSetting.value = null
  endDate.value = null
  selectedAddShiftId.value = null
  activeDialogTab.value = 'view'

  try {
    // 使用store方法获取排班设置
    await scheSettingStore.allScheSettings()
    scheduleSettings.value = scheSettingStore.scheSettings || []
    await fetchAllActiveShifts()
    showScheduleDialog.value = true
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error('打开弹窗错误:', error)
  }
}

// 获取所有激活的班次（通过shiftStore方法）
const fetchAllActiveShifts = async () => {
  try {
    loading.value = true;
    error.value = null;
    // 调用store方法而非直接调用api
    await shiftStore.fetchAllActiveShifts()
  } catch (err) {
    error.value = "获取班次列表失败";
    throw err;
  } finally {
    loading.value = false;
  }
};

// 打开新增班次对话框
const openAddShiftDialog = async () => {
  try {
    // 确保已加载所有激活班次（使用store方法）
    if (shiftStore.shifts.length === 0) {
      await fetchAllActiveShifts()
    }
    addShiftDialog.value = true
  } catch (err) {
    ElMessage.error('加载班次失败')
  }
}

// 确认新增班次（使用store方法）
const confirmAddShift = async () => {
  if (!selectedAddShiftId.value) {
    ElMessage.warning('请选择班次')
    return
  }

  // 找到选中的班次信息
  const selectedShift = shiftStore.shifts.find(
    shift => shift.shiftId === selectedAddShiftId.value
  ) as IShift

  if (!selectedShift) {
    ElMessage.warning('未找到选中的班次')
    return
  }

  // 构建排班数据
  const newSchedule: ISchedule = {
    staffId: selectedEmployee.value.staffId,
    staffName: selectedEmployee.value.staffName,
    dutyDay: selectedDate.value,
    shiftId: selectedShift.shiftId as number | string,
    deptId: currentDeptId.value,
    status: 1, // 正常执行状态
    managerName: selectedEmployee.value.staffName,
    scheShift: {
      shiftId: selectedShift.shiftId as number,
      shiftName: selectedShift.shiftName,
      startTime: selectedShift.startTime,
      endTime: selectedShift.endTime,
      workingHours: selectedShift.workingHours || null,
      status: 1, // 正常状态
      deptId: currentDeptId.value
    }
  }
  

  try {
    // 使用store的批量新增方法
    await scheduleStore.saveOrUpdateSchedules([newSchedule])
    
    // 更新本地数据并关闭对话框
    const key = `${selectedEmployee.value.staffName}_${selectedDate.value}`;
    const currentShifts = scheduleMap.value.get(key) || []
    currentShifts.push(newSchedule)
    scheduleMap.value.set(key, currentShifts)
    
    addShiftDialog.value = false
    ElMessage.success('班次新增成功')
    initEmployeeData()
  } catch (err) {
    ElMessage.error('新增班次失败')
    console.error('新增班次错误:', err)
  }
}

// 删除班次（使用store方法）
const handleDeleteShift = async (shift: ISchedule) => {
  // 1. 检查 scheduleId 是否存在
  if (!shift.scheduleId) {
    ElMessage.warning('该班次无有效 scheduleId，无法删除');
    return;
  }

  try {
    // 2. 调用 store 的 removeSchedule 方法，传递 scheduleId
    await scheduleStore.removeSchedule(shift.scheduleId); 

    // 3. 更新本地数据（从 scheduleMap 中移除该记录）
    const key = `${selectedEmployee.value.staffName}_${selectedDate.value}`;
    const currentShifts = scheduleMap.value.get(key) || [];
    const updatedShifts = currentShifts.filter(
      s => s.scheduleId !== shift.scheduleId
    );
    scheduleMap.value.set(key, updatedShifts);

    ElMessage.success(`已删除 ${shift.shiftName}`);
  } catch (err) {
    console.error('删除班次错误:', err);
    ElMessage.error('删除班次失败');
  }
};

// 批量删除选中员工在选中范围内的排班
const batchDeleteSelectedRangeSchedules = async () => {
  if (!isBatchOperationValid.value) {
    ElMessage.warning('请选择有效的员工和日期范围');
    return;
  }

  // 获取选中的员工姓名
  const selectedEmployeeNames = employeeList.value
    .filter(emp => isEmployeeSelected(emp.staffId))
    .map(emp => emp.staffName);

  // 1. 确认操作
  const confirmResult = await ElMessageBox.confirm(
    `确定要删除以下 ${selectedEmployeeNames.length} 名员工在 ${formatDateToYMD(selectedRange.value[0]!)} 至 ${formatDateToYMD(selectedRange.value[1]!)} 期间的所有排班吗？\n${selectedEmployeeNames.join('、')}`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: false,
      center: true,
      // 如果员工太多，扩大对话框宽度
      width: selectedEmployeeNames.length > 5 ? '60%' : '40%'
    }
  ).catch(() => false);

  if (!confirmResult) return;

  batchDeleting.value = true;
  
  try {
    // 2. 收集选中员工在选中日期范围内的排班ID
    const scheduleIdsToDelete: number[] = [];

    // 遍历日期区间
    const start = new Date(selectedRange.value[0]!);
    const end = new Date(selectedRange.value[1]!);
    const current = new Date(start);
    
    while (current <= end) {
      const dateStr = formatDateToYMD(current);
      
      // 只处理选中的员工
      employeeList.value
        .filter(emp => isEmployeeSelected(emp.staffId))
        .forEach(employee => {
          const key = `${employee.staffName}_${dateStr}`;
          const shifts = scheduleMap.value.get(key) || [];
          
          shifts.forEach(shift => {
            if (shift.scheduleId) {
              scheduleIdsToDelete.push(shift.scheduleId);
            }
          });
        });

      // 日期递增
      current.setDate(current.getDate() + 1);
    }

    // 3. 执行删除
    if (scheduleIdsToDelete.length === 0) {
      ElMessage.warning('选中范围内无排班数据可删除');
      return;
    }

    // 调用批量删除接口（如果有），否则循环删除
    if (scheduleStore.batchRemoveSchedules) {
      await scheduleStore.batchRemoveSchedules(scheduleIdsToDelete);
    } else {
      // 兼容没有批量删除接口的情况
      for (const id of scheduleIdsToDelete) {
        await scheduleStore.removeSchedule(id);
      }
    }

    // 4. 清理本地数据
    const cleanCurrent = new Date(start);
    while (cleanCurrent <= end) {
      const dateStr = formatDateToYMD(cleanCurrent);
      employeeList.value
        .filter(emp => isEmployeeSelected(emp.staffId))
        .forEach(employee => {
          const key = `${employee.staffName}_${dateStr}`;
          scheduleMap.value.delete(key);
        });
      cleanCurrent.setDate(cleanCurrent.getDate() + 1);
    }

    ElMessage.success(`成功删除 ${scheduleIdsToDelete.length} 条排班记录`);
    // 重新加载数据刷新界面
    await initEmployeeData();
    // 清除选择
    clearAllSelections();
  } catch (error) {
    ElMessage.error('批量删除失败：' + (error as Error).message);
    console.error('批量删除错误:', error);
  } finally {
    batchDeleting.value = false;
  }
};

// 日期禁用判断
const isDateDisabled = (date: Date, startDateStr: string) => {
  if (!startDateStr) return true;
  
  const startDate = new Date(startDateStr);
  const offset = new Date().getTimezoneOffset() * 60 * 1000;
  startDate.setTime(startDate.getTime() - offset);
  startDate.setHours(0, 0, 0, 0);
  return date < startDate;
};

// 确认排班设置
const confirmSchedule = async () => {
  if (activeDialogTab.value === 'view') {
    showScheduleDialog.value = false;
    return;
  }

  if (!selectedSettingId.value) {
    ElMessage.warning('请选择排班设置');
    return;
  }

  if (!selectedDate.value || !endDate) {
    ElMessage.warning('请选择完整的排班日期范围');
    return;
  }

  const startStr = selectedDate.value;
  const endDateObj = new Date(endDate);
  const endStr = formatDateToYMD(endDateObj);

  if (endStr < startStr) {
    ElMessage.warning('截止日期不能早于开始日期');
    return;
  }

  try {
    let periodic;
    try {
      periodic = JSON.parse(selectedSetting.value.periodicContent);
      if (!periodic.schedule || !Array.isArray(periodic.schedule) || !periodic.cycle_days) {
        ElMessage.error('排班周期配置格式错误');
        return;
      }
    } catch (e) {
      ElMessage.error('解析排班配置失败，请检查配置格式');
      console.error('解析periodicContent错误:', e);
      return;
    }

    const startCycleDay = 1;
    const targetSchedule = periodic.schedule.find((s: any) => s.day === startCycleDay);

    if (!targetSchedule) {
      ElMessage.error('周期配置中未找到第一天的班次，请检查配置');
      return;
    }

    const slots = targetSchedule.slots
      ? (Array.isArray(targetSchedule.slots) ? targetSchedule.slots : [targetSchedule.slots])
      : [];

    if (slots.length === 0) {
      ElMessage.error('该周期日无具体班次配置');
      return;
    }

    const key = `${selectedEmployee.value.staffName}_${selectedDate.value}`;
    const existingShifts = scheduleMap.value.get(key) || [];

    const newShifts: ISchedule[] = slots.map((slot: any, index: number) => {
      const [startTime, endTime] = slot.time.split('-');
      return {
        ...existingShifts[index] || {},
        staffId: selectedEmployee.value.staffId,
        staffName: selectedEmployee.value.staffName,
        dutyDay: selectedDate.value,
        shiftId: slot.shiftId,
        shiftName: slot.name || '默认班次',
        startTime: startTime ? `${startTime.trim()}:00` : '00:00:00',
        endTime: endTime ? `${endTime.trim()}:00` : '00:00:00',
        deptId: currentDeptId.value,
        status: 1,
        managerName: selectedEmployee.value.staffName,
        scheShift: {
          shiftId: slot.shiftId,
          shiftName: slot.name || '默认班次',
          startTime: startTime ? `${startTime.trim()}:00` : '00:00:00',
          endTime: endTime ? `${endTime.trim()}:00` : '00:00:00',
          workingHours: null,
          status: 1,
          deptId: currentDeptId.value
        }
      };
    });

    scheduleMap.value.set(key, newShifts);

    if (startStr === endStr) {
      ElMessage.success('已设置单日排班');
      showScheduleDialog.value = false;
      return;
    }

    generateRangeSchedule(
      selectedEmployee.value,
      selectedDate.value,
      formatDateToYMD(endDate.value),
      periodic,
      startCycleDay
    );

    ElMessage.success(`已在日期范围内设置${slots.length}个班次/天`);
    showScheduleDialog.value = false;
    handleSaveSchedule();
  } catch (error) {
    ElMessage.error('设置排班失败');
    console.error('排班设置错误:', error);
  }
};

// 生成日期范围内的多班次
const generateRangeSchedule = (
  employee: any,
  startDateStr: string,
  endDateStr: string,
  periodic: any,
  startCycleDay: number
) => {
  const startDate = new Date(startDateStr);
  const endDate = new Date(endDateStr);

  const timeDiff = endDate.getTime() - startDate.getTime();
  const totalDays = Math.floor(timeDiff / (1000 * 60 * 60 * 24)) + 1;

  for (let dayOffset = 0; dayOffset < totalDays; dayOffset++) {
    const currentDate = new Date(startDate);
    currentDate.setDate(startDate.getDate() + dayOffset);
    const currentDateStr = formatDateToYMD(currentDate);
    const key = `${employee.staffName}_${currentDateStr}`;

    let currentCycleDay = (startCycleDay + dayOffset - 1) % periodic.cycle_days + 1;
    if (currentCycleDay < 1) currentCycleDay += periodic.cycle_days;

    const daySchedule = periodic.schedule.find((s: any) => s.day === currentCycleDay);
    if (daySchedule) {
      const slots = daySchedule.slots
        ? (Array.isArray(daySchedule.slots) ? daySchedule.slots : [daySchedule.slots])
        : [];

      if (slots.length > 0) {
        const existingShifts = scheduleMap.value.get(key) || [];
        const newShifts: ISchedule[] = slots.map((slot: any, index: number) => ({
          ...existingShifts[index] || {},
          staffId: employee.staffId,
          staffName: employee.staffName,
          dutyDay: currentDateStr,
          shiftId: slot.shiftId,
          shiftName: slot.name || '默认班次',
          startTime: slot.time.split('-')[0]?.trim() + ':00' || '00:00:00',
          endTime: slot.time.split('-')[1]?.trim() + ':00' || '00:00:00',
          deptId: currentDeptId.value,
          status: 1,
          managerName: employee.staffName,
          scheShift: {
            shiftId: slot.shiftId,
            shiftName: slot.name || '默认班次',
            startTime: slot.time.split('-')[0]?.trim() + ':00' || '00:00:00',
            endTime: slot.time.split('-')[1]?.trim() + ':00' || '00:00:00',
            workingHours: null,
            status: 1,
            deptId: currentDeptId.value
          }
        }));

        scheduleMap.value.set(key, newShifts);
      }
    }
  }
};

// 保存排班到数据库（使用store方法）
const handleSaveSchedule = async () => {
  if (scheduleMap.value.size === 0) {
    ElMessage.warning('没有可保存的排班数据');
    return;
  }

  try {
    const schedulesToSave: ISchedule[] = [];
    scheduleMap.value.forEach(shifts => {
      shifts.forEach(shift => {
        const employee = employeeList.value.find(emp => emp.staffName === shift.staffName);
        console.log(shift.shiftId);
        
        if (employee) {
          schedulesToSave.push({
            scheduleId: shift.scheduleId,
            staffId: Number(employee.staffId),
            staffName: shift.staffName,
            dutyDay: shift.dutyDay,
            shiftId: Number(shift.shiftId),
            
            deptId: currentDeptId.value,
            status: shift.status || 1,
            managerName: shift.staffName,
            scheShift: shift.scheShift
          });
        }
      });
    });

    // 使用store的批量保存或更新方法
    await scheduleStore.saveOrUpdateSchedules(schedulesToSave);
    ElMessage.success('排班保存成功');
    
  } catch (error) {
    ElMessage.error(`排班保存失败：${(error as Error).message || '未知错误'}`);
    console.error('保存排班出错:', error);
  }
};

// 初始化员工和排班数据（使用store方法）
const initEmployeeData = async () => {
  try {
    // 使用store方法获取员工数据
    await staffStore.getStaffByDeptId(currentDeptId.value)
    employeeList.value = staffStore.staffList.map(staff => ({
      ...staff,
      titleName: staff.titleName || '无职称',
      positionName: staff.positionName || '无职位'
    }))
   
    const year = currentDate.value.getFullYear()
    const month = currentDate.value.getMonth() + 1
    // 使用store方法获取排班数据
    await scheduleStore.fetchSchedules({ year, month, deptId: currentDeptId.value })

    scheduleMap.value.clear();
    scheduleStore.scheduleList.forEach(schedule => {
      const key = `${schedule.staffName}_${schedule.dutyDay}`;

      if (!scheduleMap.value.has(key)) {
        scheduleMap.value.set(key, []);
      }

      const shifts = scheduleMap.value.get(key)!;
      shifts.push({
        ...schedule,
        shiftName: schedule.scheShift?.shiftName || '未知班次',
        startTime: schedule.scheShift?.startTime || '00:00:00',
        endTime: schedule.scheShift?.endTime || '00:00:00',
      });
    });
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 切换视图
const switchView = (view: 'day' | 'week' | 'month') => {
  currentView.value = view
}

// 监听日期变化重新加载数据
watch(() => [currentDate.value.getMonth(), currentView.value], () => {
  if (currentView.value === 'month') {
    initEmployeeData()
  }
}, { deep: true })

// 初始化
onMounted(() => {
  // 页面加载时通过store获取部门2的激活班次
  fetchAllActiveShifts()
  initEmployeeData()
})
</script>

<style lang="scss" scoped>
.schedule-container {
  padding: 20px;
  background-color: #f5f7fa;

  .header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;

    h2 {
      margin: 0;
      color: #303133;
      font-size: 20px;
      width: 100%;
      margin-bottom: 15px;
    }

    .view-controls {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      width: 100%;
      align-items: center;

      .month-selector {
        background: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        padding: 10px;
        width: 100%;

        .month-header {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 10px;

          .current-year {
            font-weight: bold;
            margin: 0 10px;
            font-size: 16px;
          }

          .el-button {
            padding: 0;
          }
        }

        .month-grid {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 10px;
          margin-bottom: 15px;

          .month-item {
            padding: 8px 0;
            text-align: center;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 14px;

            &:hover {
              background-color: #f5f7fa;
            }

            &.current-month {
              background-color: #ecf5ff;
              color: #409eff;
              font-weight: bold;
            }

            &.selected-month {
              background-color: #409eff;
              color: white;
              font-weight: bold;
            }
          }
        }
      }

      .view-switcher {
        margin-left: auto;
      }

      .save-schedule-btn {
        background-color: #f56c6c;
        border-color: #f56c6c;

        &:hover {
          background-color: #f78989;
          border-color: #f78989;
        }
      }
    }
  }

  .batch-actions {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }

  .schedule-content {
    margin-top: 20px;

    .view-navigation {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      gap: 15px;

      .current-period {
        font-weight: bold;
        margin-left: 10px;
      }
    }

    .day-cell {
      min-height: 80px;
      padding: 4px;
      cursor: pointer;
      display: flex;
      flex-direction: column;
      gap: 4px;

      &:hover {
        background-color: #f0f7ff;
      }
    }

    .shift-item {
      padding: 3px 2px;
      border-radius: 3px;
      text-align: center;
      font-size: 12px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      border-left: 3px solid;
      transition: all 0.2s;

      // 早班：浅青色
      &.shift-morning {
        background-color: #e6f7f0;
        border-left-color: #52c41a;
        color: #237804;
      }

      // 中班：浅绿色
      &.shift-noon {
        background-color: #e8f5ff;
        border-left-color: #1890ff;
        color: #096dd9;
      }

      // 晚班：浅紫色
      &.shift-evening {
        background-color: #f6f3ff;
        border-left-color: #722ed1;
        color: #531dab;
      }

      // 夜班：浅灰色
      &.shift-night {
        background-color: #f5f5f5;
        border-left-color: #8c8c8c;
        color: #434343;
      }

      // 默认样式（未识别时间段）
      &.shift-default {
        background-color: #fffbe6;
        border-left-color: #faad14;
        color: #864e00;
      }

      // 请假状态
      &.schedule-leave {
        background-color: #ffebee;
        border-left-color: #f44336;
        color: #b71c1c;
      }

      // 悬停效果
      &:hover {
        opacity: 0.9;
        transform: translateY(-1px);
      }
    }

    .no-schedule {
      color: #999;
      font-size: 12px;
      align-self: center;
      margin-top: auto;
      margin-bottom: auto;
    }

    :deep(.el-table) {
      th {
        background-color: #fafafa;
        white-space: pre-line;
        text-align: center;
        line-height: 1.4;
      }

      // 周末样式
      .weekend-cell {
        background-color: #f9f9f9;
      }

      // 选中日期范围样式
      .selected-date-cell {
        background-color: #fff7e6;
      }

      // 选中员工行样式
      .selected-employee-row {
        background-color: #f0f7ff !important;
      }

      // 选中员工的选中日期范围样式
      .selected-employee-date-cell {
        background-color: #ffe6e6;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          border: 1px solid #ff4d4f;
          pointer-events: none;
        }
      }
    }
  }

  // 弹窗样式
  .dialog-tabs {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }

  .current-shift-view {
    padding: 10px 0;

    h3 {
      margin: 0 0 15px 0;
      font-size: 16px;
      color: #333;
      font-weight: 600;
    }

    .loading-shifts {
      padding: 10px 0;
    }

    .error-text {
      color: #f56c6c;
      padding: 10px 0;
      text-align: center;
    }

    .shift-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      padding: 10px 0;
      min-height: 40px;
    }

    .shift-tag {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 6px 12px;
      font-size: 13px;
      max-width: 100%;
      overflow: hidden;

      .tag-name {
        font-weight: 500;
      }

      .tag-time {
        color: #666;
        font-size: 12px;
        white-space: nowrap;
      }
    }

    .no-shift {
      color: #999;
      font-size: 14px;
      padding: 10px 0;
      width: 100%;
      text-align: center;
    }

    .add-shift-btn {
      margin-top: 10px;
    }
  }
}
</style>
